<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * User类描述与用户注册，登录，发布信息，短消息等有关的控制器
 */
class User extends Controller {
    function User() {
        parent::Controller();
        $this->load->model("user_model");
        $this->load->model("book_model");
         $this->load->model("post_model");
        $this->load->helper('url');
        //$this->load->helper('cookie');
        $this->load->library('session');  //载入CI的Session库
        $this->load->library('mypagination');
        //$this->load->helper("security");
        //$this->load->helper("form");
    }

    /**
     *登录控制器
     */
    function login(){
       if($this->session->userdata('username')!=""&&$this->session->userdata('username')!=null){
          $home=base_url();
          Header("Location: $home");
          return;
       }
        $data['currentPage']=$_GET['currentpage'];
        $data['continue']=$_GET['continue'];
        $data['error']="none";
        $data['activetab']="none";
        $data['title']="登录书易";
        $data['user_status']=$this->user_model->get_user_status($data['continue']); //获取用户登录状态
        $this->load->view('user/login_view',$data);
    }

    /**
     * 登录验证函数
     */
    function login_check(){
            $input_username=$_POST['username'];
            $input_password=$_POST['passwd'];
            $status=$this->user_model->user_login_validate($input_username,$input_password);  //调用用户模型中的函数，并将参数传递过去
            $this->user_model->choose_school($this->session->userdata('school_id'));
            switch($status) {
                case 1:
                    $this->session->set_userdata('username', $input_username);
                    /*if(isset($_POST['usecookie'])){  //如果用户勾选了"记住我"选项
                      setcookie("username", $input_username, time()+10*365*24*60*60,"",".bookiki.net");
                    }*/
                    if($_POST['continue']=="no/"||$_POST['continue']=="no"){
                        $baseurl=base_url();
                        header("Location: {$baseurl}");
                        return;
                    }
                    else{
                       $previousPage=$_POST['currentpage'];
                       $previousPage=trim($previousPage,"/");  //截取网址最后出现的斜杠和问号
                       $previousPage="http://".urldecode($previousPage);
                       //地址栏中不能直接decode，否则可能出现中文参数后有分号的情况;但是实际上apache 2.2会自动decode
                       Header("Location: {$previousPage}");
                    }
                    break;
                case 0:
                      $data['currentPage']=$_POST['currentpage'];
                      $data['continue']=$_POST['continue'];
                      $data['error']="yes";
                      $data['activetab']="none";
                      $data['title']="登录书易";
                      $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
                      $this->load->view('user/login_view',$data);
                      break;
            }
      }

    /**
     * 注销用户控制器，执行注销session的操作
     */
    function logout(){
        //setcookie("username","",time()-3600);
        $this->load->library('session');
        $this->session->sess_destroy();
        $currentPage=$_GET['currentpage'];
        $continue=$_GET['continue'];
        if($continue==="no/"||$continue==="no"){
              $baseurl=base_url();
              header("Location: {$baseurl}");
        }
        else{
           $previousPage="http://".urldecode($currentPage);
           Header("Location: {$previousPage}");
        }
    }

    /**
     * 用户注册帐号控制器，跳转至填写注册信息页面
     */
    function signup($warning=""){
        $this->load->model('user_model');          //载入用户模型
        $data['warning'] = $warning;
        $data['user_status']=$this->user_model->get_user_status("no"); //获取用户登录状态
        $data['baseurl']=base_url();
        $data['title']="注册书易账户";
        $data['activetab']="none";
        if(isset($_GET['error']))
          $data['error']=urldecode($_GET['error']);
        $data['currentpage']=$_GET['currentpage'];
        //修改by abiao,原因12
        if(isset($_GET['continue']))
          $data['continue']=$_GET['continue'];
        else
          $data['continue']="no";  //默认为no
        $this->load->view('user/signup_view',$data);		//载入注册页面视图
    }

    /**
     * 用户注册时判断用户名是否已被注册
     */
    function is_usable(){
        $get_username=$_REQUEST['username'];
        if($get_username==null or $get_username==""){
            echo "用户名不能为空";
        }
        else{
            $this->load->model('user_model');          //载入用户模型
            $status=$this->user_model->if_registered($get_username);  //调用用户模型中的函数，并将参数传递过去
            if($status==1){
                echo "1"; //如果用户名已被占用
            }
            else{
                echo "0";
            }
        }
    }


    /**
     * 被Javascript调用获得下拉框中的城市列表
     */
    function get_citys(){
        
        $id = $_GET['id'];
        $citys = $this->user_model->get_citys($id);
        echo $citys;
    }


    /**
     * 被Javascript调用获得下拉框中的学校列表
     */
    function get_schools(){    
        $id = $_GET['id'];
        $schools = $this->user_model->get_schools($id);
        echo $schools;
    }

    /**
     * 被Javascript调用获得下拉框中的校园列表
     */
    function get_campuss(){
        $id = $_GET['id'];
        $campuss = $this->user_model->get_campuss($id);
        echo $campuss;
    }

    /**
     * 被Javascript调用获得下拉框中的书籍分类列表
     */
    function get_categorys(){
        $id = $_GET['id'];
        $categorys = $this->user_model->get_categorys($id);
        echo $categorys;
    }

    /**
     * 注册新用户的执行函数
     */
    function add_new_user(){
        //待修改。。。
        $warning = "";
        if( $_POST['school'] == "0" ){ //未选择学校
            //$this->warning("很遗憾，注册失败！由于您的学校未添加。单击“确定”按钮返回。");
            $warning="<p>很遗憾，注册失败！由于您的学校未添加或选择。";
            $warning=urlencode($warning);
            //$this->signup($warning);
            $cur=$_POST['currentpage'];
            $continue=$_POST['continue'];
            $link=site_url()."/user/signup?error=$warning&continue=$continue&currentpage=$cur";
            header("location: $link");
            return;
        }
        $userdata['province'] = $_POST['province'];
        $userdata['city'] = $_POST['city'];
        $userdata['school'] = $_POST['school'];
        $userdata['campus'] = $_POST['campus'];
        $this->session->set_userdata('school_id', $userdata['school']);//设置学校的id
        $this->user_model->choose_school($userdata['school']);//获取学校名字，简称
        $userdata['username']=$_POST['username'];   //获取表单中输入的用户名
        $userdata['email']=$_POST['email'];         //获取表单中输入的电子邮件地址
        $userdata['password']=$_POST['passwd'];   //获取表单中输入的密码
        $userdata['realname']=$_POST['realname'];
        $userdata['phone']=$_POST['phone'];
        $userdata['short_phone']=$_POST['short_phone'];
        $userdata['dorm']=$_POST['dorm'];
        $userdata['shopname']=$_POST['shopname'];
        $userdata['qq']=$_POST['qq'];
        $userdata['role']=0;                       //定义用户角色，0表示普通用户
        if(!preg_match("/[a-zA-Z0-9_-]{2,19}$/", $userdata['username'])){
          $error="用户名只能是英文或数字的组合";
          $continue=$_POST['continue'];
          $currentpage=$_POST['currentpage'];
          $link=site_url()."/user/signup?error=".$error."&continue=".$continue."&currentpage=".$currentpage;
          header("location: $link");
          return;
        }
        if($userdata['password']==null){
          $error="请输入密码";
          $continue=$_POST['continue'];
          $currentpage=$_POST['currentpage'];
          $link=site_url()."/user/signup?error=".$error."&continue=".$continue."&currentpage=".$currentpage;
          header("location: $link");
          return;
        }
        if($userdata['email']==null){
          $error="请输入电子邮件地址";
          $continue=$_POST['continue'];
          $currentpage=$_POST['currentpage'];
          $link=site_url()."/user/signup?error=".$error."&continue=".$continue."&currentpage=".$currentpage;
          header("location: $link");
          return;
        }
        $usable=$this->user_model->if_registered($userdata['username']);  //判断用户名是否已被占用
        switch($usable){
            case 0:  //没有注册
                $userdata['school_initials'] = $this->session->userdata("schoolinitials");
                $status=$this->user_model->add_new_user($userdata);  //调用用户模型中的函数，并将参数以数组的形式传递过去
                if($status==1){
                    $this->load->library('session');  //载入CI的Session库
                    $this->session->set_userdata('username', $userdata['username']);
                    $this->session->set_userdata('email', $userdata['email']);
                if($_POST['continue']=="no/"||$_POST['continue']=="no"){
                        $baseurl=base_url();
                        header("Location: {$baseurl}");
                    }
                else{
                    $previousPage=$_POST['currentpage'];
                    $previousPage="http://".urldecode($previousPage);
                    Header("Location: {$previousPage}");
                 }
                }
                else{
                    $error="添加新用户失败，请检查注册信息";
                    $continue=$_POST['continue'];
                    $currentpage=$_POST['currentpage'];
                    $link=site_url()."user/signup?error=".$error."&continue=".$continue."&currentpage=".$currentpage;
                    header("location: $link");
                }
                break;
            case 1:
                $error="抱歉，此用户名已经被占用，请重新选择用户名";
                $continue=$_POST['continue'];
                $currentpage=$_POST['currentpage'];
                $link=site_url()."/user/signup?error=".$error."&continue=".$continue."&currentpage=".$currentpage;
                header("location: $link");
                break;
        }
    }

    /**
     *由用户添加新学校，可能与add_new_school冲突
     */
    function add_school($warning=""){
        $data['warning'] = $warning;
        if( $warning == "" ){
            $data['username'] = $_GET['u'];
            $data['email'] = $_GET['e'];
        }
        else{
            $data['username'] = "";
            $data['email'] = "";
        }
        $data['activetab']="none";
        $data['title']="添加学校";
        $data['user_status']=$this->user_model->get_user_status("no"); //获取用户登录状态
        $this->load->view("user/add_school",$data);
    }

     /**
     *由用户添加新学校，可能与add_school冲突
     */
    function add_new_school(){
       $count = 0;
       $campus = array();
       foreach($_POST as $k => $v)
       {          
          if( strpos($k,"campus") ){
              $campus[$k] = $v;
          }
          else
            $data[$k] = $v;
          $count++;
       }
       if( $count != 15 && $count != 20 ){
          $home=base_url();
          Header("Location: $home");
          return;
       }
        $data["campus"] = $campus;
        $warning = "";
        if( $data['city']=="0" || $data['province'] == '0'){
            $warning = "省名或城市名为空！";
            $this->add_school($warning);
            return;
        }
        if ( trim($data['name']) == "" ){
            $warning = "学校名为空！";
            $this->add_school($warning);
            return;
        }
        if( trim($data['username']) == "" || trim($data['email']) == "" ){
            $warning = "请填写邮箱和用户名以便我们发邮件提醒您，并领取积分。";
            $this->add_school($warning);
            return;
        }
        $this->user_model->add_new_school($data);
        $warning = "非常感激您添加了学校!";
        $this->add_school($warning);
    }

    /**
     * 切换学校,被首页学校名称下"切换学校"调用后的控制器
     */
    function change_school($warning=""){
          $data['warning'] = $warning;
          $data['activetab']="change_school";
          $data['title']="切换城市";
          $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
          $data['username'] = "";
          $data['email'] = "";
          $data['username'] = $this->session->userdata('username');
          if( $data['username'] != '' )
              $data['email'] = $this->session->userdata('email');
          $this->load->view("change_school",$data);
    }
    
    /*
     * 切换城市的时候选择一个学校,切换学校的执行控制器
     */
    function select_a_school(){
        $warning = "";
        if( $_POST['school'] == '0' ){
            $warning = "你还没有选择学校！";
            $this->change_school($warning);
            return;
        }
        $this->session->set_userdata("school_id",$_POST['school']);
        $this->user_model->choose_school($this->session->userdata('school_id'));
        //回到首页
        $home=base_url();
        Header("Location: $home");
    }

    //warning信息
    function warning( $warning ) {
        echo "<script charset=\"UTF-8\" language=\"javascript\">";
        echo "window.alert('" . $warning. "')";
        echo "</script>";
        echo "<script language=\"javascript\">";
        echo "location.href=\"javascript:history.go(-1)\"";
        echo "</script>";
        return;
    }


     /**
     *展示用户的订单
     */
    function my_order(){
       $username=$this->session->userdata('username');
        if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
       else{
          $user_info = $this->user_model->get_userinfo($username);
       }
       $data['user_info'] = $user_info;
       $data['activetab']="none";
       $data['activenav']="order";
       $data['title']="我的订单";
       $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
       $this->load->view('user/my_order_view',$data);
    }


    /**
     *展示用户资料
     */
    function my_profile($warning=""){
       $username=$this->session->userdata('username');
        if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
       else{
          $user_info = $this->user_model->get_userinfo($username);
       }
       $user_info->province_name = $this->user_model->get_province($user_info->province_id)->pname;
       $user_info->city_name = $this->user_model->get_city($user_info->city_id)->cname;
       $user_info->campus_name=$this->user_model->get_campus($user_info->campus_id);
       $user_info->school_name = $this->user_model->get_schoolname($user_info->school_id);
       $data['user_info'] = $user_info;
       $data['warning'] = $warning;
       $data['activetab']="none";
       $data['activenav']="profile";
       $data['title']="我的个人信息";
       $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
       $this->load->view('user/my_profile_view',$data);
    }

    /**
     *展示用户的卖出书籍资料信息
     */
    function my_salepost($error=""){
        $username=$this->session->userdata('username');
        $siteurl=site_url();
        $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        if($username==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
            Header("Location: $loginPage");
       }
       $school=$this->user_model->get_school($username);
       //配置分页函数
        if(isset($_GET['curpage']))
           $offset=$_GET['curpage'];
        else
           $offset=0;
         if(!isset($_GET['totalrows'])){
           $result= $this->post_model->get_mysalepost(1,$username,$school,0,$offset,8);  //total=1,dealed=0,perpage=8
           $config['total_rows'] =$result[0]->number;
        }
        else{
           $config['total_rows'] =$_GET['totalrows'];
        }
        $config['page_query_string'] = TRUE;
        $link="user/my_salepost?go=yes&totalrows={$config['total_rows']}";
        $config['base_url'] = site_url($link);
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['per_page']=8;
        $this->mypagination->initialize($config);      
      $data['posts']=$this->post_model->get_mysalepost(0,$username,$school,0,$offset,8);
      $data['error']=$error;
      $data['activetab']="myshop";
      $data['activenav']="saleposts";
      $data['title']="我出售的书籍";
      $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
      $this->load->view('user/my_salepost_view',$data);
   }

   /**
    * 在首页置顶卖出书籍信息
    */
   function up_salepost(){
        $username=$this->session->userdata('username');
        $siteurl=site_url();
        $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        if($username==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
            Header("Location: $loginPage");
       }
       if(isset($_GET['upall']))
         $upall=1;
       else
         $upall=0;
       if(isset($_GET['bookid']))
         $bookid=$_GET['bookid'];
       else
         $bookid=-1;
       $school=$this->user_model->get_school($username);
       $status=$this->post_model->up_mysalepost($username,$bookid,$upall,$school);
       if($status==0){
         $error="抱歉，你的积分不够，无法置顶所有书籍";
         $this->my_salepost($error);
       }
       else{
         $error="置顶卖出书籍的信息成功！";
         $this->my_salepost($error);
       }
   }

   /**
    * 在用户资料中显示所有已经出售的书籍信息
    */
   function my_dealedsalepost(){
        $username=$this->session->userdata('username');
        $siteurl=site_url();
        $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        if($username==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
            Header("Location: $loginPage");
       }
       $school=$this->user_model->get_school($username);
       //配置分页函数
        if(isset($_GET['curpage']))
           $offset=$_GET['curpage'];
        else
           $offset=0;
         if(!isset($_GET['totalrows'])){
           $result= $this->post_model->get_mysalepost(1,$username,$school,1,$offset,8);  //total=1,dealed=1,perpage=8
           $config['total_rows'] =$result[0]->number;
        }
        else{
           $config['total_rows'] =$_GET['totalrows'];
        }
        $config['page_query_string'] = TRUE;
        $link="user/my_dealedsalepost?go=yes&totalrows={$config['total_rows']}";
        $config['base_url'] = site_url($link);
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['per_page']=8;
        $this->mypagination->initialize($config);
      $data['posts']=$this->post_model->get_mysalepost(0,$username,$school,1,$offset,8);
      $data['activetab']="myshop";
      $data['activenav']="dealedsaleposts";
      $data['title']="已卖出的书籍";
      $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
      $this->load->view('user/my_dealedsalepost_view',$data);
   }

   /**
     *展示用户的求购书籍资料信息
     */
    function my_wantedpost($error=""){
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
      $school=$this->user_model->get_school($username);

      //配置分页函数
        if(isset($_GET['curpage']))
           $offset=$_GET['curpage'];
        else
           $offset=0;
         if(!isset($_GET['totalrows'])){
           $result= $this->post_model->get_mywantedpost(1,$username,$school,0,$offset,8);  //total=1,dealed=1,perpage=8
           $config['total_rows'] =$result[0]->number;
        }
        else{
           $config['total_rows'] =$_GET['totalrows'];
        }
        $config['page_query_string'] = TRUE;
        $link="user/my_wantedpost?go=yes&totalrows={$config['total_rows']}";
        $config['base_url'] = site_url($link);
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['per_page']=8;
        $this->mypagination->initialize($config);
      $data['posts']=$this->post_model->get_mywantedpost(0,$username,$school,0,$offset,8);
      $data['activetab']="myshop";
      $data['activenav']="wantedposts";
      $data['title']="我求购的书籍";
      $data['error']=$error;
      $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
       $this->load->view('user/my_wantedpost_view',$data);
   }

   /**
    * 在首页置顶求购书籍信息
    */
   function up_wantedpost(){
        $username=$this->session->userdata('username');
        $siteurl=site_url();
        $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        if($username==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
            Header("Location: $loginPage");
       }
       if(isset($_GET['upall']))
         $upall=1;
       else
         $upall=0;
       if(isset($_GET['bookid']))
         $bookid=$_GET['bookid'];
       else
         $bookid=-1;
       $school=$this->user_model->get_school($username);
       $status=$this->post_model->up_mywantedpost($username,$bookid,$upall,$school);
       if($status==0){
         $error="抱歉，你的积分不够，无法置顶所有求购的信息";
         $this->my_wantedpost($error);
       }
       else{
         $error="置顶求购书籍的信息成功！";
         $this->my_wantedpost($error);
       }
   }

   /**
    * 在用户资料中显示所有已经交易的求购书籍信息
    */
   function my_dealedwantedpost(){
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
      $school=$this->user_model->get_school($username);

      //配置分页函数
        if(isset($_GET['curpage']))
           $offset=$_GET['curpage'];
        else
           $offset=0;
         if(!isset($_GET['totalrows'])){
           $result= $this->post_model->get_mywantedpost(1,$username,$school,1,$offset,8);  //total=1,dealed=1,perpage=8
           $config['total_rows'] =$result[0]->number;
        }
        else{
           $config['total_rows'] =$_GET['totalrows'];
        }
        $config['page_query_string'] = TRUE;
        $link="user/my_dealedwantedpost?go=yes&totalrows={$config['total_rows']}";
        $config['base_url'] = site_url($link);
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['per_page']=8;
        $this->mypagination->initialize($config);
      $data['posts']=$this->post_model->get_mywantedpost(0,$username,$school,1,$offset,8);
      $data['activetab']="myshop";
      $data['activenav']="dealedwantedposts";
      $data['title']="我买到的书籍";
      $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
       $this->load->view('user/my_dealedwantedpost_view',$data);
   }

   /**
    * 读取收到的短消息主题
    */
   function read_msg_theme(){
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }

      //配置分页函数
        if(isset($_GET['curpage']))
           $offset=$_GET['curpage'];
        else
           $offset=0;
        $config['page_query_string'] = TRUE;
         if(!isset($_GET['totalrows'])){
           $result= $this->user_model->get_msg_theme(0,1,$username,$offset,8);
           $config['total_rows'] =$result[0]->number;
        }
        else{
           $config['total_rows'] =$_GET['totalrows'];
        }
        $link="user/read_msg_theme?go=yes&totalrows={$config['total_rows']}";
        $config['base_url'] = site_url($link);
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['per_page']=8;
        $this->mypagination->initialize($config);
      $data['msgs']=$this->user_model->get_msg_theme(0,0,$username,$offset,8);
      $data['activetab']="none";
      $data['activenav']="allmsg";
      $data['title']="阅读短信";
      $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
      $this->load->view('user/rec_msg_view',$data);
   }

   /**
    * 读取发送给别人的短消息主题
    */
   function read_send_msg_theme(){
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
       //配置分页函数
        if(isset($_GET['curpage']))
           $offset=$_GET['curpage'];
        else
           $offset=0;
        $config['page_query_string'] = TRUE;
         if(!isset($_GET['totalrows'])){
           $result= $this->user_model->get_msg_theme(1,1,$username,$offset,8);
           $config['total_rows'] =$result[0]->number;
        }
        else{
           $config['total_rows'] =$_GET['totalrows'];
        }
        $link="user/read_send_msg_theme?go=yes&totalrows={$config['total_rows']}";
        $config['base_url'] = site_url($link);
        $config['per_page']=8;
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $this->mypagination->initialize($config);
        $data['msgs']=$this->user_model->get_msg_theme(1,0,$username,$offset,8);
        $data['activetab']="none";
        $data['activenav']="sentmsg";
        $data['title']="已发短消息";
        $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('user/send_msg_view',$data);
   }

  /**
   *读取发送或收到的短消息正文
   */
  function read_msg_content(){
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
       else{
         $msgid=$_GET['msgid'];
         $data['msg']=$this->user_model->get_msg_content($_GET['kind'],$username,$msgid);
       }
       $data['kind'] =$_GET['kind'];//收到的信息还是发送的信息
       $data['activetab']="myshop";
       if($data['kind']=="send")
         $data['activenav']="sentmsg";
       else
         $data['activenav']="allmsg";
       $data['title']="阅读短消息";
       $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
       $this->load->view('user/msg_content_view',$data);
   }

  /**
   *对短消息的操作：回复/删除/无操作
   */
  function msg_handle(){
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
       if( $_GET['click'] == '回复' ){
           $msg['theme'] = "回复“" .$_GET['theme']. "”";
           $msg['receiver'] = $_GET['sender_id'];
           $msg['content'] = "";
           $this->edit_msg2("",$msg,0);
       }
       elseif( $_GET['click'] == '删除' ){
           $_GET['read'] = 1;
           if( $_GET['kind'] == "send" ){
                $this->del_msg(0);
           }
           else{
                $this->del_msg(1);
           }
       }
   }

   /**
    *编辑个人资料
    */
   function edit_info(){
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
       $warning = "";
       if( $_POST['is_changed'] == '1' && ($_POST['school'] == '0') ){
           $warning = "很抱歉，由于学校还没有选择或尚未添加，无法完成修改！";
           $this->my_profile($warning);
           return;
       }
       if( $_POST['is_changed'] == '1' ){
           $data['province'] = $_POST['province'];
           $data['city'] = $_POST['city'];
           $data['school'] = $_POST['school'];
           $data['campus'] = $_POST['campus'];
           $this->session->set_userdata("school_id",$data['school']);
           $this->user_model->choose_school($this->session->userdata('school_id'));
       }
       $data['user_id'] = $this->session->userdata("username");       
       $data['shopname']=$_POST['shopname'];
       $data['name']=$_POST['name'];
       $data['phone'] = $_POST['phone'];
       $data['short_phone'] = $_POST['short_phone'];
       $data['dorm'] = $_POST['dorm'];
       $data['qq'] = $_POST['qq'];
       $data['email'] = $_POST['email'];       
       $this->user_model->edit_info($data,$_POST['is_changed']);
       $warning = "修改成功！";       
       $this->my_profile($warning);
   }

   /**
    * 编辑等待发送的消息，系统可能自动增加”你好，我想买你的。。“等内容
    */
   function edit_msg(){
       $username=$this->session->userdata('username');
       $siteurl=site_url();
       $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
       if($username==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.htmlentities(urlencode($currentPage));
            Header("Location: $loginPage");
       }
      if(isset($_GET['receiver']))
        $msg['receiver'] =urldecode($_GET['receiver']);
      else
        $msg['receiver'] = "";
      if(isset($_GET['content'])){
        $title=mb_substr($_GET['content'],0,18,"UTF-8")."...";
        if($_GET['type']=="sale"){
          $msg['theme'] ="出售".$title;
          $msg['content'] ="你好，我有《".$_GET['content']."》可以卖给你。";
        }
        else if($_GET['type']=="wanted"){
             $msg['theme'] ="求购".$title;
             $msg['content'] ="你好，我想买你的《".$_GET['content']."》。";
        }
      }
      else{
         $msg['content']="";
         $msg['theme']="";
      }
      
      $data['warning'] = "";
      $data['msg'] = $msg;
      $data['activetab']="none";
      $data['activenav']="newmsg";
      $data['title']="编辑短信";
      $data['user_status']=$this->user_model->get_user_status("no"); //获取用户登录状态
      $this->load->view('user/edit_msg_view',$data);
   }

   function edit_msg2($warning,$msg,$suc){
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
      $data['warning'] = $warning;
      $data['msg'] = $msg;
      $data['activetab']="none";
      $data['activenav']="newmsg";
      $data['title']="编辑短信";
      $data['user_status']=$this->user_model->get_user_status("no"); //获取用户登录状态
      if( $suc == 0 )
        $this->load->view('user/edit_msg_view',$data);//重新返回编辑页面
      else
        $this->load->view('user/send_msg_suc',$data);//成功
   }

   /**
    *删除短消息
    */
   function del_msg($kind){ 
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
       $msg_id = $_GET['msgid'];
       $read = $_GET['read'];
       $this->user_model->delete_msg($kind,$this->session->userdata('username'),$msg_id,$read);
       if( $kind == 1 )
            $this->read_msg_theme();//
       else
            $this->read_send_msg_theme();
   }

   /**
    *删除短消息
    */
   function del_msg2(){ //删除短消息
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
       $msg_id = $_GET['msgid'];
       $read = $_GET['read'];
       if( $_GET['kind'] == 'send')
        $kind = 0;
       else
        $kind = 1;
       $this->user_model->delete_msg($kind,$this->session->userdata('username'),$msg_id,$read);
       if( $kind == 1 )
            $this->read_msg_theme();//
       else
            $this->read_send_msg_theme();
   }

   /**
    *执行发送短消息的任务
    */
   function send_msg(){
       $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
       $count = 0;
       foreach($_POST as $k => $v)
       {
          $msg[$k] = $v;
          $count++;
       }
       if( $count != 3 ){
           $home=base_url();
          Header("Location: $home");
          return;
       }
       
        if( $msg['receiver'] == '' ) {
            $this->edit_msg2("收件人不能为空!",$msg,0);
        }
        elseif( $msg['theme'] == '' ) {
            $this->edit_msg2("标题不能为空!",$msg,0);
        }
        elseif( $msg['content'] == '') {
            $this->edit_msg2("内容不能为空!",$msg,0);
        }
        elseif( mb_strlen($msg['content'],'UTF-8') > 300 ) {
            $this->edit_msg2("内容不能超过300个字符!",$msg,0);
        }
        elseif( mb_strlen($msg['theme'],'UTF-8') > 100 ) {
            $this->edit_msg2("标题不能超过100个字符!",$msg,0);
        }
        else{
            $warning = $this->user_model->send_msg($this->session->userdata('username'),$msg['receiver'],$msg['theme'],$msg['content']);
            if( $warning == "no_receiver" ){
                $this->edit_msg2("收件人不存在！",$msg,0);
            }
            else{
                $this->edit_msg2("发送成功！",$msg,1);
            }
        }
   }

   /**
    *发送短消息后返回首页
    */
   function msg_send_suc_back(){
      $username=$this->session->userdata('username');
       if($username==""){
          $home=base_url();
          Header("Location: $home");
          return;
       }
      
      $this->read_msg_theme();
   }

    //查看购物车
    function shop_car(){
        $username=$this->session->userdata('username');
        $this->load->library('session');
        $siteurl=site_url();
        $currentPage=$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        if(($this->session->userdata('username'))==""){
            $loginPage=$siteurl.'/user/login?continue=yes&currentpage='.urlencode($currentPage);
            Header("Location: $loginPage");
        }
        $data['baseurl']=base_url();
        $data['title']="我的购物车";
        $data['userinfo']=$this->user_model->get_userinfo($username);
        $data['shop_car'] = $this->user_model->get_shop_car($username);
        $data['activetab']="none";
        $data['user_status']=$this->user_model->get_user_status(); //获取用户登录状态
        $this->load->view('user/my_shop_car',$data);		//载入注册页面视图
       
    }

}
?>